package white_list

import (
	"fmt"
	"parking-lot-go-admin/controller"
	"parking-lot-go-admin/model"
	"parking-lot-go-admin/model/cars"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/tealeg/xlsx/v3"
)

func Download(c *gin.Context) {

	requestDataMap := make(map[string]interface{})
	c.ShouldBindJSON(&requestDataMap)

	where, page, pageSize := controller.WhereStructure(requestDataMap)
	where["1= ? "] = 1

	//查询信息
	var carsWhiteListStruct cars.CarsWhiteListStruct
	var carsWhiteListData []cars.CarsWhiteListStruct
	model.GetModelData(
		model.Db,
		carsWhiteListStruct.TableName(),
		&carsWhiteListData,
		model.QueryOptions{
			Page:       page,
			PageSize:   pageSize,
			Conditions: where,
			OrderBy:    "id desc",
			Debug:      true,
		},
	)

	// 创建新的Excel文件
	file := xlsx.NewFile()

	// 创建工作表
	sheet, err := file.AddSheet("白名单车辆")
	if err != nil {
		fmt.Println("Error adding sheet:", err)
		return
	}

	// 设置表头
	row := sheet.AddRow()
	row.WriteSlice(&[]string{"名称", "手机号", "车牌号码", "车牌颜色", "车辆类型", "客户类型", "有效期", "状态"}, -1)

	carNoColor := map[int]string{
		1: "蓝牌",
		3: "黄牌",
		6: "绿牌",
		7: "白牌",
		8: "黑牌",
	}

	carType := map[int]string{
		1: "小型车",
		2: "中型车",
		3: "大型车",
		4: "其他",
	}

	orderType := map[int]string{
		0: "如之停车",
		1: "小强停车",
		2: "泊安飞",
	}

	//数据格式化并写入Excel
	for _, v := range carsWhiteListData {
		deleteStatus := "过期"
		if v.DeletedAt.IsZero() {
			deleteStatus = "正常"
		}

		row := sheet.AddRow()
		row.WriteSlice(&[]interface{}{
			v.Name,
			v.Mobile,
			v.CarNumber,
			carNoColor[v.CarNoColor],
			carType[v.CarType],
			orderType[v.OrderType],
			v.OutTime.Format("2006-01-02 15:04:05"),
			deleteStatus,
		}, -1)
	}

	// 设置HTTP头部信息
	fileName := fmt.Sprintf("白名单车辆导出-%d.xlsx", time.Now().Unix())
	c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
	c.Header("Cache-Control", "max-age=0")

	// 保存文件到浏览器输出
	if err := file.Write(c.Writer); err != nil {
		return
	}

}
